package ipc;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rddl.RDDL;
import java.util.Random;

public class TimedRounds {
	Agent agent;//to save UCT tree
	IPCSimulator world;//world - kept consistent with server
	IPCSimulator simulatedworld;//for UCT
	List<Agent> agents = new ArrayList<Agent>();
	myDD _spudd;
	Arbiter<IPCState, IPCAction> arbiter;
	/*
	 * UCT Parameters
	 */
	final double UCTConstant = 1.0;
	final int sparseSample = 10;
	long instTime;
	
	public TimedRounds(RDDL rddl, String instance_name, String spudd_file, int horizon, long inst_time,int numRounds, long seed, int fHorizon, String agentStr) throws Exception{
		
		System.out.println("Instance time: " +inst_time);

		Main.timeLog.log("Timedrounds " + instance_name + " "  + inst_time);
		
		Main.paramLog.log("Sparse smaple " + sparseSample);
		
		instTime = inst_time;
		
		System.out.println("Starting UCT "+instance_name);
		Main.activityLog.log("Starting UCT "+instance_name);
		
		long round_time = (long)(inst_time)-10000L;
		Main.paramLog.log("Round time " + round_time);
		
		System.out.println("Round time " + round_time);

		try {
			world = new IPCSimulator(rddl, instance_name, seed);
			world.setInitialState();
		} catch (Exception e) {
			Main.exceptionLog.log(e.getMessage());
			System.exit(1);
		}    	
        try {
			simulatedworld = new IPCSimulator(rddl, instance_name, seed);
			simulatedworld.setInitialState();
		} catch (Exception e) {
			Main.exceptionLog.log(e.getMessage());
			System.exit(1);
		}
		
		
		
		if( agentStr.equals("BOPP") )
			agent = new TimedUCT<IPCState, IPCAction>(UCTConstant, sparseSample, simulatedworld, fHorizon, seed, instance_name, horizon);
		else if( agentStr.equals("SPUDD"))
			agent = new SpuddAgent<IPCState, IPCAction>(instance_name, horizon, simulatedworld);
		else if( agentStr.equals("RANDOM"))
			agent = new RandomAgent<IPCState, IPCAction>(simulatedworld, seed);
		else if( agentStr.equals("NOOP"))
			agent = new NOOPAgent<IPCState, IPCAction>();
		else{
			throw new Exception("Unknown agent string");
		}
			
		
		agents.add(agent);
		arbiter = new Arbiter(world, agents);
		
//		try {
//			Thread.currentThread().sleep((long)(instTime*0.5d));
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		try{
			Thread.currentThread().sleep(10000);		
		}catch(Exception e){
		}

		arbiter.runSimulations(simulatedworld, numRounds, round_time, horizon);
	}

	public double getVariance() {
		return arbiter.getVariance();
	}

	public double getMean() {
		return arbiter.getMean();
	}
	
	
}
